package cn.sytton.taffecloud.service.system.service.impl;

import cn.sytton.taffecloud.common.db.model.PageParam;
import cn.sytton.taffecloud.common.servlet.service.BaseService;
import cn.sytton.taffecloud.common.excel.ExcelImport;
import cn.sytton.taffecloud.common.excel.model.ExcelImportResult;
import cn.sytton.taffecloud.service.system.entity.*;
import cn.sytton.taffecloud.service.system.mapper.RoleMapper;
import cn.sytton.taffecloud.service.system.mapper.RoleMenuFuncMapper;
import cn.sytton.taffecloud.service.system.mapper.RoleMenuMapper;
import cn.sytton.taffecloud.service.system.mapper.RoleUserMapper;
import cn.sytton.taffecloud.service.system.service.IRoleService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色服务层
 *
 * @author skyrock
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService extends BaseService<RoleEntity> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private RoleMenuFuncMapper roleMenuFuncMapper;
    @Resource
    private RoleUserMapper roleUserMapper;

    @Override
    public PageInfo<RoleEntity> findListPage(PageParam pp) {
        return findListPage(pp, roleMapper);
    }

    @Override
    public RoleEntity findById(String id) {
        return roleMapper.findById(id);
    }

    @Validated
    @Override
    public void create(RoleEntity entity) {
        roleMapper.create(entity);
    }

    @Override
    public void update(RoleEntity entity) {
        roleMapper.update(entity);
    }

    @Override
    public void delete(String... ids) {
        roleMapper.delete(ids);
    }

    @Override
    public Map<String, Object> findMenu(String roleId) {
        List<String> menuIds = roleMenuMapper.findMenuIdByRoleId(roleId);
        List<String> funcKeys = roleMenuFuncMapper.findFuncKeyByRoleId(roleId);

        Map<String, Object> result = new HashMap<>();
        result.put("menuIds", menuIds);
        result.put("funcKeys", funcKeys);

        return result;
    }

    @Override
    public void authMenu(Auth auth) {
        for(String menuIdFuncKey : auth.getDeleteMenuIdFuncKeys()) {
            if (StringUtils.hasText(menuIdFuncKey)) {
                String[] falseFuncKeyObject = menuIdFuncKey.split("#");
                String menuId = falseFuncKeyObject[0];
                String funcKey = falseFuncKeyObject[1];
                roleMenuFuncMapper.deleteByRoleIdMenuIdFuncKey(auth.getRoleId(), menuId, funcKey);
            }
        }
        for (String menuId : auth.getDeleteMenuIds()) {
            if (StringUtils.hasText(menuId)) {
                roleMenuMapper.deleteByRoleIdMenuId(auth.getRoleId(), menuId);
            }
        }
        for (String menuId : auth.getAddMenuIds()) {
            if (StringUtils.hasText(menuId)) {
                RoleMenuEntity roleMenuEntity = new RoleMenuEntity();
                roleMenuEntity.setMenuId(menuId);
                roleMenuEntity.setRoleId(auth.getRoleId());
                roleMenuMapper.create(roleMenuEntity);
            }
        }
        for (String menuIdFuncKey : auth.getAddMenuIdFuncKeys()) {
            if (StringUtils.hasText(menuIdFuncKey)) {
                String[] trueFuncKeyObject = menuIdFuncKey.split("#");
                String menuId = trueFuncKeyObject[0];
                String funcKey = trueFuncKeyObject[1];
                RoleMenuFuncEntity roleMenuFuncEntity = new RoleMenuFuncEntity();
                roleMenuFuncEntity.setMenuId(menuId);
                roleMenuFuncEntity.setFuncKey(funcKey);
                roleMenuFuncEntity.setRoleId(auth.getRoleId());
                roleMenuFuncMapper.create(roleMenuFuncEntity);
            }
        }
    }

    @Override
    public PageInfo<UserEntity> findUserListPage(String roleId, PageParam pp) {
        setPageParams(pp);
        boolean exclude = pp.getParams().containsKey("exclude") && Boolean.parseBoolean(pp.getParams().get("exclude").toString());
        return new PageInfo<>(exclude ?  roleUserMapper.findUserListForExclude(roleId) : roleUserMapper.findUserList(roleId));
    }

    @Override
    public void addUsers(RoleUserEntity entity) {
        for(String userId : entity.getUserIds()) {
            entity.setUserId(userId);
            roleUserMapper.create(entity);
        }
    }

    @Override
    public void removeUsers(RoleUserEntity entity) {
        roleUserMapper.removeUsers(entity);
    }

    @Override
    public void updateRoleStatus(RoleEntity entity) {
        roleMapper.updateRoleStatus(entity);
    }

    @Override
    public String importData(MultipartFile file) {
        ExcelImport<RoleEntity> excelImport = new ExcelImport<>(RoleEntity.class, file);
        excelImport.importExcel();
        for (ExcelImportResult<RoleEntity> data : excelImport.getResult()) {
            try {
                if (data.isSuccess()) {
                    roleMapper.create(data.getEntity());
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                data.fail(e.getMessage());
            }
        }
        return excelImport.writeImportResult();
    }
}
